const fs = require('fs')
const path = require('path')

const parser = function (file) {
  const lastArray = [
    {
      name: 'phase',
      regex: /^Starting phase (\d+)\/4: /g,
      value: '',
      pass: false,
    },
    { name: 'table', regex: /^Computing table (\d+)/g, value: '', pass: false },
    { name: 'backpropagating', regex: /^Backpropagating on table (\d+)/g, value: '', pass: false },
    { name: 'compressing', regex: /^Compressing tables (\d+)/g, value: '', pass: false },
  ]

  const parserArray = [
    { name: 'id', regex: /^ID: ([a-z0-9]+)/g, value: '', pass: false },
    {
      name: 'start',
      regex: /^(2021[0-9\-\.:T]+)  chia.plotting.create_plots/g,
      value: '',
      pass: false,
    },
    { name: 'plot_size', regex: /^Plot size is: (\d+)/g, value: '', pass: false },
    { name: 'buffer_size', regex: /^Buffer size is: (\d+)MiB/g, value: '', pass: false },
    { name: 'buckets', regex: /^Using (\d+) buckets/g, value: '', pass: false },
    { name: 'threads', regex: /^Using (\d+) threads of stripe size/g, value: '', pass: false },
    {
      name: 'phase1',
      regex: /^Time for phase 1 = (\d+)\.\d+ seconds. CPU /g,
      value: '',
      pass: false,
    },
    {
      name: 'phase2',
      regex: /^Time for phase 2 = (\d+)\.\d+ seconds. CPU /g,
      value: '',
      pass: false,
    },
    {
      name: 'phase3',
      regex: /^Time for phase 3 = (\d+)\.\d+ seconds. CPU /g,
      value: '',
      pass: false,
    },
    {
      name: 'phase4',
      regex: /^Time for phase 4 = (\d+)\.\d+ seconds. CPU /g,
      value: '',
      pass: false,
    },
    { name: 'copy_time', regex: /^Copy time = (\d+)\.\d+ seconds/g, value: '', pass: false },
    { name: 'total_time', regex: /^Total time = (\d+)\.\d+ seconds/g, value: '', pass: false },
    { name: 'file', regex: /^Renamed final file from \".+\" to (\".+\")/g, value: '', pass: false },
    {
      name: 'temporary',
      regex: /^Starting plotting progress into temporary dirs: (.*) and /g,
      value: '',
      pass: false,
    },
    { name: 'file_size', regex: /^Final File size: (\d+\.\d+ .*)/g, value: '', pass: false },
  ]

  const data = fs.readFileSync(file, 'utf8')
  const lines = data.split(/\r?\n/)
  for (let index = 0; index < lines.length; index++) {
    const line = lines[index]
    for (let i = 0; i < parserArray.length; i++) {
      const regex = parserArray[i]
      if (!regex.pass) {
        const res = regex.regex.exec(line)
        if (res) {
          regex.pass = true
          regex.value = res[1]
        }
      }
    }
    for (let i = 0; i < lastArray.length; i++) {
      const regex = lastArray[i]
      const res = regex.regex.exec(line)
      if (res) {
        regex.value = res[1]
      }
    }
  }
  // console.log(lastArray)
  const obj = {}
  for (let index = 0; index < parserArray.length; index++) {
    const elem = parserArray[index]
    obj[elem.name] = elem.value
  }
  let progress = 0
  if (!!obj['total_time']) {
    progress = 100
  } else if (lastArray[0].value == '1') {
    progress = (6 * parseInt(lastArray[1].value)).toFixed(0)
  } else if (lastArray[0].value == '2') {
    const temp = parseInt(lastArray[2].value)
    progress = (42 + 3 * (8 - temp)).toFixed(0)
  } else if (lastArray[0].value == '3') {
    progress = (62 + parseInt(lastArray[3].value) * 6).toFixed(0)
  } else if (lastArray[0].value == '4') {
    progress = 98
  }
  // 1	Computing table 1 计算表1	1%
  // 1	Computing table 2 计算表2	6%
  // 1	Computing table 3 计算表3	12%
  // 1	Computing table 4 计算表4	20%
  // 1	Computing table 5 计算表5	28%
  // 1	Computing table 6 计算表6	36%
  // 1	Computing table 7 计算表7	42%
  // 2	Backpropagating on table 7 在表7上反向传播	43%
  // 2	Backpropagating on table 6 在表6上反向传播	48%
  // 2	Backpropagating on table 5 在表5上反向传播	51%
  // 2	Backpropagating on table 4 在表4上反向传播	55%
  // 2	Backpropagating on table 3 在表3上反向传播	58%
  // 2	Backpropagating on table 2 在表2上反向传播	61%
  // 3	Compressing tables 1 and 2 压缩表1和表2	66%
  // 3	Compressing tables 2 and 3 压缩表2和表3	73%
  // 3	Compressing tables 3 and 4 压缩表3和表4	79%
  // 3	Compressing tables 4 and 5 压缩表4和表5	85%
  // 3	Compressing tables 5 and 6 压缩表5和表6	92%
  // 3	Compressing tables 6 and 7 压缩表6和表7	98%
  // 4	Write checkpoint tables 编写检查点表	100%

  obj['progress'] = parseInt(progress)
  obj['plot_size'] = parseInt(obj['plot_size'])
  obj['buffer_size'] = parseInt(obj['buffer_size'])
  obj['buckets'] = parseInt(obj['buckets'])
  obj['threads'] = parseInt(obj['threads'])
  obj['phase1'] = parseInt(obj['phase1'])
  obj['phase2'] = parseInt(obj['phase2'])
  obj['phase3'] = parseInt(obj['phase3'])
  obj['phase4'] = parseInt(obj['phase4'])
  obj['copy_time'] = parseInt(obj['copy_time'])
  obj['total_time'] = parseInt(obj['total_time'])
  obj['start'] = new Date(obj['start']).getTime()


  obj['phase1'] = parseFloat(((obj['phase1'])?obj['phase1']/3600: 0).toFixed(2))
  obj['phase2'] = parseFloat(((obj['phase2'])?obj['phase2']/3600: 0).toFixed(2))
  obj['phase3'] = parseFloat(((obj['phase3'])?obj['phase3']/3600: 0).toFixed(2))
  obj['phase4'] = parseFloat(((obj['phase4'])?obj['phase4']/3600: 0).toFixed(2))
  obj['copy_time'] = parseFloat(((obj['copy_time'])?obj['copy_time']/3600: 0).toFixed(2))
  obj['total_time'] = parseFloat(((obj['total_time'])?obj['total_time']/3600: 0).toFixed(2))

  return obj
}

exports.parser_log = (dirs, debug) => {
  const res = []
  const root = path.join(dirs)

  readDirSync(root)
  function readDirSync(path) {
    const pa = fs.readdirSync(path)
    pa.forEach(function (ele, index) {
      const info = fs.statSync(path + '/' + ele)
      if (info.isDirectory()) {
        // console.log('dir: ' + ele)
        readDirSync(path + '/' + ele)
      } else {
        debug && console.log('path: ' + ele)
        const mtime = fs.statSync(path + '/' + ele).mtime.getTime()
        if (debug || ((new Date().getTime() - mtime) / 1000 / 60 < 60)) {
          res.push(parser(path + '/' + ele))
        }
      }
    })
  }
  return res
}
// // interesting data from logfiles as regex
//       public static Regex plotSizeRg = new Regex("^Plot size is: (\\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex bufferSizeRg = new Regex("^Buffer size is: (\\d+)MiB", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex bucketsRg = new Regex("^Using (\\d+) buckets", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex threadsRg = new Regex("^Using (\\d+) threads of stripe size (\\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex startDateRg = new Regex("^Starting phase 1/4: Forward Propagation into tmp files\\.\\.\\. (.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex phase1Rg = new Regex("^Time for phase 1 = (\\d+)\\.\\d+ seconds. CPU \\((\\d+\\.\\d+)%\\) ", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex phase2Rg = new Regex("^Time for phase 2 = (\\d+)\\.\\d+ seconds. CPU \\((\\d+\\.\\d+)%\\) ", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex phase3Rg = new Regex("^Time for phase 3 = (\\d+)\\.\\d+ seconds. CPU \\((\\d+\\.\\d+)%\\) ", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex phase4Rg = new Regex("^Time for phase 4 = (\\d+)\\.\\d+ seconds. CPU \\((\\d+\\.\\d+)%\\) ", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex copyTime = new Regex("^Copy time = (\\d+)\\.\\d+ seconds", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex totalTimeRg = new Regex("^Total time = (\\d+)\\.\\d+ seconds", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex plotNameRg = new Regex("^Renamed final file from \".+\" to (\".+\")", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex currentBucketRg = new Regex("^\\tBucket (\\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex phase1Table = new Regex("^Computing table (\\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex phase2Table = new Regex("^Backpropagating on table (\\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex phase3Table = new Regex("^Compressing tables (\\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex tmpFolders = new Regex("^Starting plotting progress into temporary dirs: (.*) and (.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex writePloblemRg = new Regex("^Only wrote \\d+ of \\d+ bytes at", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex couldNotOpenFile = new Regex("^Could not open", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex readPloblemRg = new Regex("^Only read \\d+ of \\d+ bytes at", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex copyPloblemRg = new Regex("^Could not copy ", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex approximateWorkingSpace = new Regex("^Approximate working space used \\(without final file\\): (\\d+\\.\\d+ .*)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex finalFileSize = new Regex("^Final File size: (\\d+\\.\\d+ .*)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex destinationDirectory = new Regex("^Final Directory is: (.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex caughtPlottingError = new Regex("^Caught plotting error: .*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//       public static Regex queueSize = new Regex(".* Starting plot \\d+/(\\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
